package com.wjjun.base.ui.window

import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.wjjun.base.BR
import com.wjjun.base.ui.activity.BaseActivity
import com.wjjun.base.ui.listener.IViewListener
import com.wjjun.base.ui.viewmodel.BaseWindowViewModel
import com.wjjun.base.utils.ViewModelFactory

/**
 * 基础绑定popup window
 *
 * author : wangjunjun
 * date   : 2022/6/8
 * desc   :
 */
abstract class BaseWindow<VM : BaseWindowViewModel, VD : ViewDataBinding>(val context: BaseActivity) :
        PopupWindow(context), IViewListener {

    protected lateinit var viewDataBinding: VD
    protected var viewModel: VM? = null

    init {
        buildViewModel()
        buildViewBinding()
        bindViewModel()

        initLayout()
        initContent()
    }

    open fun buildViewModel() {
        if( isNewViewModel()){
            viewModel = ViewModelFactory.createNewViewModel(
                context,
                this.javaClass,
                BaseWindowViewModel::class.java)
        }else{
            viewModel = ViewModelFactory.createViewModel(
                context,
                this.javaClass,
                BaseWindowViewModel::class.java)
        }
    }

    /**
     * 如果碰到viewModel复用,开启它
     */
    open fun isNewViewModel() :Boolean{
        return false
    }

    private fun buildViewBinding() {
        var layoutId = viewModel?.getLayoutId() ?: getLayoutId()
        viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(context), layoutId, null, false)
        contentView = viewDataBinding.root
    }

    private fun bindViewModel() {
        viewDataBinding.setVariable(BR.viewModel, viewModel)
        viewDataBinding.setVariable(BR.listener, this)
    }

    @LayoutRes
    protected open fun getLayoutId(): Int {
        return 0
    }

    open fun initLayout() {
        width = LinearLayout.LayoutParams.WRAP_CONTENT
        height = LinearLayout.LayoutParams.WRAP_CONTENT
        isFocusable = true
        isOutsideTouchable = true
        inputMethodMode = INPUT_METHOD_NEEDED
    }

    abstract fun initContent()

}